<?php


namespace App\Http\Services\FormBuilder\Segments;


use App\Http\Services\BrowserDetect;
use App\Http\Services\FormBuilder\Elements\Field;

class MoneySelectorBracketWithStockLimit extends BaseMoneySelectorBracket
{
    protected $attributes = [
        'class' => 'fields two',
        'id'    => 'goal_options',
    ];

    public function render()
    {
        if (!BrowserDetect::isMobile()) {
            $this->removeClass('two')->addClass('four');
        }
        $hasActiveOption = false;
        $html            = '<div';
        $html .= $this->renderAttributes();
        $html .= '>';
        if ($this->label) {
            $html .= $this->label;
        }
        $fields = collect($this->brackets)->map(function ($item) use (&$hasActiveOption) {
            $bracketButton = new BracketButtonWithStockLimit($item);
            $bracketButton->unit($this->unit);
            if (!(collect($item)->get('stock', 0) === 0) && $item['money'] == $this->defaultMoney && !$hasActiveOption) {
                $bracketButton->addClass('active');
                $hasActiveOption = true;
            }
            $field = new Field($bracketButton);
            if (collect($item)->get('stock', 0) === 0) {
                $field->addClass('disabled');
            }
            $field->addClass('flex');

            return $field;
        })->all();
        foreach ($fields as $field) {
            $html .= $field;
        }
        $html .= '</div>';

        return $html;
    }
}